from PySide6.QtWidgets import (
    QDialog, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, 
    QDialogButtonBox, QTabWidget, QWidget, QFormLayout,
    QSpinBox, QComboBox, QPushButton, QTextEdit
)
from PySide6.QtCore import Qt

class PropertyEditDialog(QDialog):
    """组件属性编辑对话框"""
    
    def __init__(self, comp_type, comp_id, comp_config, parent=None):
        super().__init__(parent)
        self.comp_type = comp_type
        self.comp_id = comp_id
        self.comp_config = comp_config.copy()  # 复制一份，避免直接修改原配置
        
        self.setWindowTitle(f"编辑属性 - {comp_id}")
        self.setMinimumWidth(500)
        self.setMinimumHeight(400)
        
        # 主布局
        layout = QVBoxLayout(self)
        
        # 创建标签页控件
        self.tab_widget = QTabWidget()
        
        # 基本属性标签页
        self.basic_tab = QWidget()
        self.setup_basic_tab()
        self.tab_widget.addTab(self.basic_tab, "基本属性")
        
        # 动作属性标签页 (按钮和滑动条)
        if comp_type in ['button', 'slider']:
            self.action_tab = QWidget()
            self.setup_action_tab()
            self.tab_widget.addTab(self.action_tab, "动作属性")
        
        # 绑定属性标签页 (文本显示)
        if comp_type == 'text_display':
            self.binding_tab = QWidget()
            self.setup_binding_tab()
            self.tab_widget.addTab(self.binding_tab, "绑定属性")
        
        layout.addWidget(self.tab_widget)
        
        # 按钮
        self.button_box = QDialogButtonBox(
            QDialogButtonBox.StandardButton.Save | 
            QDialogButtonBox.StandardButton.Cancel
        )
        self.button_box.accepted.connect(self.accept)
        self.button_box.rejected.connect(self.reject)
        layout.addWidget(self.button_box)
    
    def setup_basic_tab(self):
        """设置基本属性标签页"""
        layout = QFormLayout(self.basic_tab)
        layout.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow)
        
        # ID（只读）
        self.id_edit = QLineEdit(self.comp_id)
        self.id_edit.setReadOnly(True)
        layout.addRow("组件ID:", self.id_edit)
        
        # 根据组件类型添加不同的属性控件
        if self.comp_type == 'button':
            # 按钮文本
            self.text_edit = QLineEdit(self.comp_config.get('text', ''))
            layout.addRow("按钮文本:", self.text_edit)
            
        elif self.comp_type == 'text_display':
            # 文本内容
            self.text_edit = QTextEdit(self.comp_config.get('text', ''))
            self.text_edit.setMinimumHeight(100)
            layout.addRow("文本内容:", self.text_edit)
            
        elif self.comp_type == 'slider':
            # 滑动条标签
            self.label_edit = QLineEdit(self.comp_config.get('label', ''))
            layout.addRow("滑动条标签:", self.label_edit)
            
            # 最小值
            self.min_spin = QSpinBox()
            self.min_spin.setRange(-9999, 9999)
            self.min_spin.setValue(self.comp_config.get('min', 0))
            layout.addRow("最小值:", self.min_spin)
            
            # 最大值
            self.max_spin = QSpinBox()
            self.max_spin.setRange(-9999, 9999)
            self.max_spin.setValue(self.comp_config.get('max', 100))
            layout.addRow("最大值:", self.max_spin)
            
            # 默认值
            self.default_spin = QSpinBox()
            self.default_spin.setRange(-9999, 9999)
            self.default_spin.setValue(self.comp_config.get('default', 50))
            layout.addRow("默认值:", self.default_spin)
            
            # 单位
            self.unit_edit = QLineEdit(self.comp_config.get('unit', ''))
            layout.addRow("单位:", self.unit_edit)
    
    def setup_action_tab(self):
        """设置动作属性标签页 - 用于按钮和滑动条"""
        layout = QFormLayout(self.action_tab)
        layout.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow)
        
        # 获取动作配置
        action = self.comp_config.get('action', {})
        if not action:
            # 如果不存在，创建默认动作配置
            action = {'type': 'write', 'characteristic': '', 'data': ''}
            self.comp_config['action'] = action
        
        # 操作类型
        self.action_type_combo = QComboBox()
        self.action_type_combo.addItems(['write', 'read', 'notify'])
        current_type = action.get('type', 'write')
        index = self.action_type_combo.findText(current_type)
        if index >= 0:
            self.action_type_combo.setCurrentIndex(index)
        layout.addRow("操作类型:", self.action_type_combo)
        
        # 特征UUID
        self.char_uuid_edit = QLineEdit(action.get('characteristic', ''))
        layout.addRow("特征UUID:", self.char_uuid_edit)
        
        # 根据组件类型处理数据字段
        if self.comp_type == 'button':
            # 数据 (十六进制)
            self.data_edit = QLineEdit(action.get('data', ''))
            layout.addRow("数据(十六进制):", self.data_edit)
            
        elif self.comp_type == 'slider':
            # 数据模板
            self.data_template_edit = QLineEdit(action.get('data_template', ''))
            layout.addRow("数据模板:", self.data_template_edit)
            
            # 帮助标签
            help_label = QLabel(
                "使用{value}作为占位符，例如：\n"
                "固定格式: 01020304{value:02x}0506\n"
                "格式说明: {value:02x} - 十六进制2位, {value:04x} - 十六进制4位\n"
                "         {value:02d} - 十进制2位"
            )
            help_label.setWordWrap(True)
            help_label.setStyleSheet("color: #666; font-size: 11px;")
            layout.addRow("", help_label)
    
    def setup_binding_tab(self):
        """设置绑定属性标签页 - 用于文本显示"""
        layout = QFormLayout(self.binding_tab)
        layout.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow)
        
        # 获取绑定配置
        binding = self.comp_config.get('binding', {})
        if not binding:
            # 如果不存在，创建默认绑定配置
            binding = {'characteristic': '', 'format': 'hex'}
            self.comp_config['binding'] = binding
        
        # 特征UUID
        self.binding_char_uuid_edit = QLineEdit(binding.get('characteristic', ''))
        layout.addRow("绑定特征UUID:", self.binding_char_uuid_edit)
        
        # 显示格式
        self.format_combo = QComboBox()
        self.format_combo.addItems(['hex', 'text'])
        current_format = binding.get('format', 'hex')
        index = self.format_combo.findText(current_format)
        if index >= 0:
            self.format_combo.setCurrentIndex(index)
        layout.addRow("显示格式:", self.format_combo)
    
    def get_updated_config(self):
        """获取更新后的配置"""
        # 根据组件类型更新基本属性
        if self.comp_type == 'button':
            self.comp_config['text'] = self.text_edit.text()
            
        elif self.comp_type == 'text_display':
            self.comp_config['text'] = self.text_edit.toPlainText()
            
        elif self.comp_type == 'slider':
            self.comp_config['label'] = self.label_edit.text()
            self.comp_config['min'] = self.min_spin.value()
            self.comp_config['max'] = self.max_spin.value()
            self.comp_config['default'] = self.default_spin.value()
            self.comp_config['unit'] = self.unit_edit.text()
        
        # 更新动作属性
        if self.comp_type in ['button', 'slider']:
            action = self.comp_config.get('action', {})
            action['type'] = self.action_type_combo.currentText()
            action['characteristic'] = self.char_uuid_edit.text()
            
            if self.comp_type == 'button':
                action['data'] = self.data_edit.text()
            elif self.comp_type == 'slider':
                action['data_template'] = self.data_template_edit.text()
            
            self.comp_config['action'] = action
        
        # 更新绑定属性
        if self.comp_type == 'text_display':
            binding = self.comp_config.get('binding', {})
            binding['characteristic'] = self.binding_char_uuid_edit.text()
            binding['format'] = self.format_combo.currentText()
            self.comp_config['binding'] = binding
        
        return self.comp_config 